<?php


namespace App\Http\Controllers;

use App\Services\StoreService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class StoreController extends Controller
{
    private const ZSDJ = [
        3   => '三星',
        5   => '五星'
    ];

    private const JSDJ = [
        "JSDJ1" => "普通技师",
        "JSDJ2" => "二星技师",
        "JSDJ3" => "三星技师",
        "JSDJ4" => "四星技师",
    ];

    private const STORE_LEVEL = [
        1   => '外星人点',
        2   => '授权店',
        3   => '直营店',
        4   => '旗舰店',
        5   => '其他',
    ];

    public function index()
    {
        return view('store.index');
    }

    public function about()
    {
        return view('store.about');
    }

    /**
     * 店铺图片
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function storeImages(Request $request)
    {
        return response()->json([
            'code'  => 0,
            'data'  => [
                'top_images' =>
                [
                    [
                        'id'    => 1,
                        'store_name'    => '测试店铺1',
                        'image_url'        => 'https://www.starbucks.com.cn/design-studio/images/SZCC_FACADE.JPG',
                    ],
                    [
                        'id'    => 2,
                        'store_name'    => '测试店铺2',
                        'image_url'        => 'https://www.starbucks.com.cn/design-studio/images/SZCC_FACADE.JPG',
                    ],
                    [
                        'id'    => 3,
                        'store_name'    => '测试店铺三',
                        'image_url'        => 'https://www.starbucks.com.cn/design-studio/images/SZCC_FACADE.JPG',
                    ]

                ],
                'bottom_images' => [
                    [
                        'small' =>  'https://www.starbucks.com.cn/design-studio/images/15-Inspiration/small/10.jpg',
                        'big'   => 'https://www.starbucks.com.cn/design-studio/images/15-Inspiration/13.jpg',
                    ],
                    [
                        'small' => 'https://www.starbucks.com.cn/design-studio/images/15-Inspiration/small/15.jpg',
                        'big'   => 'https://www.starbucks.com.cn/design-studio/images/15-Inspiration/15.jpg',
                    ],
                    [
                        'small' => 'https://www.starbucks.com.cn/design-studio/images/15-Inspiration/small/15.jpg',
                        'big'   => 'https://www.starbucks.com.cn/design-studio/images/15-Inspiration/15.jpg',
                    ],
                    [
                        'small' => 'https://www.starbucks.com.cn/design-studio/images/15-Inspiration/small/15.jpg',
                        'big'   => 'https://www.starbucks.com.cn/design-studio/images/15-Inspiration/15.jpg',
                    ]
                ]
            ],
        ]);
    }

    public function detail(int $id)
    {
        if (empty($id)) {
            return response()->json([
                'code' => 1000,
                'msg'  => '缺少数据'
            ]);
        }
        $data = DB::table('users')->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id')
            ->where('users.id', $id)
            ->select('users.*', 'store_info.id as store_id', 'store_info.persons', 'store_info.picture_url', 'store_info.qrcode_url', 'store_info.open_time', 'store_info.store_level', 'store_info.start_date', 'store_info.end_date', 'store_info.store_code', 'store_info.video_url', 'store_info.detail', 'province_master.simplified_chiness_value as province', 'store_info.close_time', 'store_info.honor_images')
            ->first();

        if (empty($data)) {
            return response()->json([
                'code'  => 0,
                'data'  => []
            ]);
        }

        $features = DB::table('store_features')->where('store_id', $data->store_id)->where('is_delete', 0)->where('type', 1)->select('picture_url', 'detail')->get();
        $pictureUrl = DB::table('store_features')->where('store_id', $data->store_id)->where('is_delete', 0)->where('type', 2)->select('picture_url', 'detail')->get();
        if (!empty($features)) {
            $featureData = [];
            foreach ($features as $feature) {
                $featureData[] = [
                    'picture_url' => 'https://warranty.xpel.com.cn'  . $feature->picture_url,
                    'detail'      => $feature->detail,
                ];
            }
        }
        if (!empty($pictureUrl)) {
            $pictureData = [];
            foreach ($pictureUrl as $feature) {
                $pictureData[] = [
                    'picture_url' => 'https://warranty.xpel.com.cn'  . $feature->picture_url,
                    'detail'      => $feature->detail,
                ];
            }
        }
        $result = [
            'id'            => $data->id,
            'address'       => $data->address,
            'open_time'     => $data->open_time ?? '',
            'close_time'    => $data->close_time ?? '',
            'store_name'    => $data->abbr,
            'phone'         => $data->phone_number,
            'province'      => $data->province,
            'lng'           => $data->lng,
            'lat'           => $data->lat,
            'concat_name'   => $data->first_name,
            'store_level'   => self::STORE_LEVEL[$data->mdtype],
            'store_code'    => $data->store_code,
            'start_date'    => $data->start_date ?: date('Y-m-d'),
            'end_date'      => $data->end_date ?: date('Y-m-d'),
            'zsdj'          => self::ZSDJ[$data->zsdj] ?? '',
            'jsdj'          => self::JSDJ[$data->jsdj] ?? '',
            'video_url'     => $data->video_url,
            'qrcode_url'    => $data->qrcode_url ? 'https://warranty.xpel.com.cn'. $data->qrcode_url : 'https://warranty.xpel.com.cn/upload/202105/rytAnkDjiXpNEQWbH0tIEvF4JICoxC.png',
            'features'      => $featureData ?? [],
            'detail'        => $data->detail,
            'picture_url'   => $pictureData ?? [],
            'persons'       => $data->persons ? json_decode($data->persons, true) : [],
        ];

        return response()->json([
            'code'  => 0,
            'data'  => $result
        ]);
    }

    /**
     * 获取附近店家
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNearBy(Request $request)
    {
        $lng = $request->input('lng');
        $lat = $request->input('lat');
        $dist = $request->input('dist') ?: 2000;
        $city = $request->input('city');
        $district = $request->input('district');
        if ($dist < 5) {
             $dist = 5;
        }
        $storeName = $request->input('store_name') ?: '';

        if (empty($lng) || 0.0 > $lng || 180.0 < $lng) {
            return response()->json([
                'code' => 1000,
                'msg'  => '经度范围错误'
            ]);
        }

        if (empty($lat) || 0.0 > $lat || 90.0 < $lat) {
            return response()->json([
                'code' => 1000,
                'msg'  => '纬度范围错误'
            ]);
        }

        $sql = 'SELECT  
  users.id, `abbr`, first_name, address, phone_number, lng, lat, zsdj, (  
    6371 * acos (  
      cos ( radians(' . $lat . ') )  
      * cos( radians( lat ) )  
      * cos( radians( lng ) - radians('. $lng . ') )  
      + sin ( radians(' . $lat . ') )  
      * sin( radians( lat ) )  
    )  
  ) AS distance  
FROM users LEFT JOIN cities ON users.city=cities.id WHERE users.deleted_at is null and users.status=1 and users.creator_id not in (1515,1554,2784,2803,2815,2823,2835)';

        if (!empty($storeName)) {
            $sql .= ' AND abbr LIKE "%' . urldecode($storeName) . '%"';
        }
        if (!empty($district)) {
            $sql .= ' AND district LIKE "' . $district . '%"';
        }

        if (!empty($city)) {
            $sql .= ' AND cities.simplified_chiness_value LIKE "' . $city . '%"';
        }

        $sql .= ' HAVING distance <' . $dist . ' ORDER BY zsdj DESC, distance ASC';
        $data = DB::select($sql);
        if (empty($data)) {
            return response()->json([
                'code'  => 0,
                'data'  => []
            ]);
        }

        $list = [];
        foreach ($data as $item) {
            $list[] = [
                'id'    => $item->id,
                'store_name'  => $item->abbr,
                'concat_name' => $item->first_name,
                'address'     => $item->address,
                'city'        => '',
                'distance'    => round($item->distance, 2),
                'phone'       => $item->phone_number,
                'lng'         => $item->lng,
                'lat'         => $item->lat,
                'zsdj'        => $item->zsdj,
            ];
        }

        return response()->json([
            'code'  => 0,
            'data'  => $list
        ]);
    }

    public function sendCode(Request $request)
    {
        $mobile = trim($request->input('mobile'));
        if (empty($mobile)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '缺少手机号'
            ]);
        }
        $user = DB::table('users')->where('phone_number', $mobile)->where('user_type', 5)
            ->whereNull('deleted_at')
            ->first();

        if (empty($user)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '手机号不存在'
            ]);
        }
        //$code = mt_rand(1111, 9999);
        $code = 1234;
        Redis::set('wx:login:' . $user->id, $code);
        Redis::expire('wx:login:' . $user->id, 120);

        return response()->json([
            'code'  => 0,
            'msg'   => 'success',
        ]);
    }

    public function login(Request $request)
    {
        $mobile = trim($request->input('mobile'));
        $code = trim($request->input('code'));
        if (empty($mobile) || empty($code)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '缺少数据'
            ]);
        }
        $user = DB::table('users')->where('phone_number', $mobile)->where('user_type', 5)
            ->whereNull('deleted_at')
            ->first();

        if (empty($user)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '手机号不存在'
            ]);
        }

        $result = Redis::get('wx:login:' . $user->id);
        if (!$result) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '验证码错误'
            ]);
        }

        $token = md5(mt_rand(1111111, 9999999) . uniqid() . time());

        Redis::set('wx:user:login:success:' . $token, $user->id);
        Redis::expire('wx:user:login:success:' . $token, 86400);

        return response()->json([
            'code'  => 0,
            'msg'   => 'success',
            'data'  => [
                'token' => $token,
                'store_name'  => $user->company_name,
                'mobile'    => $mobile,
                'province'  => '',
                'city'      => '',
                'address'   => $user->address
            ]
        ]);
    }

    public function mobileLogin(Request $request)
    {
        $mobile = trim($request->input('mobile'));
        if (empty($mobile)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '缺少数据'
            ]);
        }
        $user = DB::table('users')
            ->where('phone_number', $mobile)
            ->where('user_type', 3)
            ->where('status',1)
            ->whereNull('deleted_at')
            ->first();

        if (!$user) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '手机号不存在'
            ]);
        }

        if ($user->status != 1){
            return response()->json([
                'code'  => 1001,
                'msg'   => '门店已停用'
            ]);
        }

       // $token = md5(mt_rand(1111111, 9999999) . uniqid() . time());

//        Redis::set('wx:user:login:success:' . $token, $user->id);
//        Redis::expire('wx:user:login:success:' . $token, 86400);

        return response()->json([
            'code'  => 0,
            'msg'   => 'success',
            'data'  => [
                'token' => $user->id,
                'store_name'  => $user->company_name,
                'mobile'    => $mobile,
                'province'  => '',
                'city'      => '',
                'address'   => $user->address
            ]
        ]);
    }
}
